//
//  HybridWebVc.swift
//  mall-ios
//
//  Created by Meak Tsui on 2018/12/3.
//  Copyright © 2018 Meak Tsui. All rights reserved.
//

import Foundation
import UIKit
import WebKit
import MTHybrid
import SnapKit
import Shared

let CUSTUMER_USER_AGENT = "SDHybrid"

enum DisplayMode:String {
    case normal
    case gradient
    case fade
}

struct DisplayConfig {
    var color:UIColor?
    var bgColor:UIColor?
    var bgImgURL:URL?
    var displayMode:DisplayMode = .normal
    
    static let `default` = DisplayConfig()
}

class HybridWebVc: UIViewController {
    
    var displayConfig:DisplayConfig = .default
    var requestURL:URL!
    
    lazy var hybrid:MTHybrid = {
        let config = MTHybridConfig()
        config.custumerUA = CUSTUMER_USER_AGENT
        config.register(handlers: SystemNs.actionHandlers())
        config.register(handlers: AppNs.actionsHandlers())
        config.register(handlers: DeviceNs.actionHandlers())
        config.register(handlers: NavNs.actionHandlers())
        config.register(handlers: TabNs.actionHandlers())


        config.register(producers: DeviceNs.producers())
        let hybrid = MTHybrid(config)
        return hybrid
    }()
    
    lazy var webView:WKWebView = {
        let config = WKWebViewConfiguration()
        config.processPool = MTWKWebviewPool.shared.processPool
        let web = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height),configuration: config)
        web.allowsLinkPreview = false
        web.allowsBackForwardNavigationGestures = false
        let cookieWID = HTTPCookie(properties: [
            HTTPCookiePropertyKey(rawValue: "HttpOnly"):"false"])
        return web
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configHeader()
        hybrid.bind(webView)
        hybrid.vc = self
        hybrid.naviDelegate = self
        self.webView.load(URLRequest(url: self.requestURL,timeoutInterval:10))
        
        self.view.addSubview(webView)
        self.view.backgroundColor = UIColor.hexInt(0xf0f0f0)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
    
    deinit {
        hybrid.disable()
    }
    
    var statusBarStyle:UIStatusBarStyle = .default
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        get {
            return statusBarStyle
        }
        set {
            statusBarStyle = newValue
        }
    }
    
    
    @objc fileprivate func reload() {
        reloadRequest()
    }
    
    func reloadRequest() {
        self.webView.load(URLRequest(url: self.webView.url ?? requestURL,timeoutInterval:10))
    }
    
    func loadFin() {
        self.webView.isHidden = false
    }
    
    func loadFail() {
        self.webView.isHidden = true
    }
    
    func startLoad() {
    }
    
    func configHeader() {
        if displayConfig.displayMode == .fade {
            self.navigationController?.hidesBarsOnSwipe = true
        }
        guard let bgColor = displayConfig.bgColor else {
            return
        }
        switch  displayConfig.displayMode {
        case .gradient:
            self.navigationController?.navigationBar.setBackgroundImage(bgColor.trans2Image(), for: .default)
            self.navigationController?.navigationBar.shadowImage = UIImage()
            let barImageView = self.navigationController?.navigationBar.subviews.first
            barImageView?.alpha = 0
        default:
            self.navigationController?.navigationBar.backgroundColor = bgColor
        }
    }
}

extension HybridWebVc:WKNavigationDelegate {
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        self.startLoad()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.navigationItem.title = self.webView.title
        self.loadFin()
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        let err = error as NSError
        //忽略用户操作行为导致的请求取消异常
        if err.code == NSURLErrorCancelled {
            return
        }
        self.loadFail()
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        dPrint("加载\(requestURL.absoluteString)失败")
        //忽略用户操作行为导致的请求取消异常
        if (error as NSError).code == NSURLErrorCancelled {
            return
        }
        self.loadFail()
    }
    
}

extension HybridWebVc:UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if displayConfig.displayMode == .gradient {
            let minAlphaOffset:CGFloat = 64.0
            let maxAlphaOffset:CGFloat = 200.0
            let offset = scrollView.contentOffset.y
            let alpha = (offset - minAlphaOffset) / (maxAlphaOffset - minAlphaOffset)
            let barImageView = self.navigationController?.navigationBar.subviews.first
            barImageView?.alpha = alpha
        }
    }
}
